package com.tuyenmonkey.mkloader.type;

import com.tuyenmonkey.mkloader.model.Arc;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.RectFloat;

public class Whirlpool extends LoaderView {
  private Arc[] arcs;
  private int numberOfArc;
  private float[] rotates;

  public Whirlpool() {
    numberOfArc = 3;
  }

  @Override public void initializeObjects() {
    float r = Math.min(width, height) / 2f;
    arcs = new Arc[numberOfArc];
    rotates = new float[numberOfArc];

    for (int i = 0; i < numberOfArc; i++) {
      float d = r / 4 + i * r / 4;
      arcs[i] = new Arc();
      arcs[i].setColor(color);
      arcs[i].setOval(new RectFloat(center.getPointX() - d, center.getPointY() - d, center.getPointX() + d, center.getPointY() + d));
      arcs[i].setStartAngle(i * 45);
      arcs[i].setSweepAngle(i * 45 + 90);
      arcs[i].setStyle(Paint.Style.STROKE_STYLE);
      arcs[i].setWidth(r / 10f);
    }
  }

  @Override public void setUpAnimation() {
    for (int i = numberOfArc - 1; i >= 0; i--) {
      final int index = i;

      AnimatorValue fadeAnimator = new AnimatorValue();
      fadeAnimator.setLoopedCount(AnimatorValue.INFINITE);
      fadeAnimator.setDuration((i + 1) * 1000);
      fadeAnimator.setCurveType(Animator.CurveType.ACCELERATE);
      fadeAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
        @Override
        public void onUpdate(AnimatorValue animatorValue, float v) {
            if (index/2 == 0){
                rotates[index] = v * -360;
            }else {
                rotates[index] = v * 360;
            }

          if (invalidateListener != null) {
            invalidateListener.reDraw();
          }
        }
      });
      fadeAnimator.start();
    }
  }

  @Override public void draw(Canvas canvas) {
    for (int i = 0; i < numberOfArc; i++) {
      canvas.save();
      canvas.rotate(rotates[i], center.getPointX(), center.getPointY());
      arcs[i].draw(canvas);
      canvas.restore();
    }
  }
}
